﻿using Cysharp.Threading.Tasks;
using DG.Tweening;
using moai_kun_v2;
using System;
using UnityEngine;
using UnityEngine.SceneManagement;

public class GameMgr:MonoBehaviour
{
  
    public static GameMgr Instance;

    private void Awake()
    {
        if (Instance != null && Instance != this)
        {
            Destroy(gameObject);
            return;

        }
        Instance = this;
        DontDestroyOnLoad(gameObject);
    }
    public void ResetGame() 
    {
        //SceneManager.LoadScene(0);
        UISystem.Instance.Show(UI_TYPE.START);
    }


    private int _resetCount=3;
    public int ResetCount 
    {
        get { return _resetCount; }
        set 
        {
            if (_resetCount <= 0) 
            {
                _resetCount = 0;
        
            }
            else if (_resetCount != value) 
            {
                _resetCount = value;
            }
            
        }
    }

    private int _mapIndex=1;

    public int MapIndex 
    {
        get { return _mapIndex; }
        set { _mapIndex= value; }
    }

    private MainActor _mainActor;
    public MainActor CurrentPlayer => _mainActor;
    public async UniTask StartGame() 
    {
        await SceneManager.LoadSceneAsync(MapIndex);
        _mainActor = GameObject.FindObjectOfType<MainActor>();
        
        CurrentPlayer.OnDead += Failure;
        CurrentPlayer.OnDeadComplete += UniTask.Action(IsContinueGame);

        LevelManager.Instance.ResetLevel(MapIndex);


        CurrentPlayer.ResetStatus();
        UISystem.Instance.Show(UI_TYPE.LOAD,()=>UISystem.Instance.Show(UI_TYPE.GAME));
        TimeManager.Instance.StartTime();
    }

    private async UniTaskVoid IsContinueGame()
    {
        if (ResetCount <= 0) 
        {
            GameOver();
        }
        else 
        {
            await StartGame();
        }
    }

    public void Pause() 
    {
        TimeManager.Instance.PauseTime();
    }

    public async UniTask Success() 
    {
        MapIndex++;
        ResetCount++;
        await StartGame();
    }

    public void Failure() 
    {
        TimeManager.Instance.ResetTime();
        ResetCount--;
        CurrentPlayer.OnDead -= Failure;
       
        CurrentPlayer.OnDeadComplete -= UniTask.Action(IsContinueGame);
        
    }


    public void GameOver() 
    {
        UISystem.Instance.Show(UI_TYPE.GAME_OVER);
       
    }
   
}

